/**
 * 下载中心管理
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2015-01-28 11:40:12
 * @for 下载中心管理.html
 * @version $1.0$
 */
var BSTMG = BSTMG || {};
BSTMG.downloadManager = {
	init: function(){
		var that = this;
		/* 上传图片，图片裁剪 */
		that.uploadImgAndCut();
		/* 确定提交数据 */
		that.submitDownloadFrom();
	},
	uploadImgAndCut: function(){
		var $downloadform = $("#downloadform"),
			$proicon = $downloadform.find(".proicon"),
			$cutimg = $("#showImg"),
			$hinputimg = $("#hd_imgurl"),
			$show_imgurl = $("#show_imgurl");
		var	$device_version = $downloadform.find(".device_version");
		var $confirmcut = $(".confirmcut"),
			$preview = $("#preview-pane"),
			$previewimg = $("#crop_preview"),
			panelwidth = $preview.width(),
			panelheight = $preview.height(),
			jQcrop = null,
			original_width = null,
			original_height = null;
		// 图片裁剪
		$proicon.on("change",".file_input",function(){
			var $this = $(this),
				value = $this.val();
			if(!/.(gif|jpg|jpeg|png|JPG|PNG)$/.test( value )) {
			    BSTYUN.dialog.warn("图片类型必须是.jpeg,jpg,png中的一种");
			    return false;
			};
			$.ajaxFileUpload({
				url:"/uploadFile/image?attachType=3&objectName=goodsDownload",
				secureuri:false,
				fileElementId:"hd_imgurl",
				dataType:"json",
				success:function(data) {
					if(data.message == "上传文件成功") {
						var path = data.path;
						$show_imgurl.val( path );
						try{
							// 初始化裁剪
							var original_img = new Image();
							original_img.src = path ;
							original_img.onload = function(){
								original_width = this.width;
								original_height = this.height;
							};
							$cutimg.load(function(){
								reJcropImg();
							}).attr('src', path );
							$previewimg.attr('src', path );
						}catch(e){
							if( window.console ) {
								console.warn("图片裁剪插件初始化失败！");
							};
						};
					}else{
						$show_imgurl.val( "" );
						BSTYUN.dialog.warn( data.message );						
					};
				},
				error:function (data, status, e) {
					BSTYUN.dialog.warn("图片上传失败,请重新选择图片！");
				}
			});
		});
		$confirmcut.on("click",".btn",function(){
			if( !!!jQcrop ) {
				BSTYUN.dialog.warn("请上传一张图片裁剪！");
				return false;
			};
			var url = $show_imgurl.val();
			var scale = jQcrop.tellSelect(), //裁剪的尺寸
				bound = jQcrop.getBounds();		// 获取图片实际尺寸，格式为：[w, h]
			var rx = original_width / bound[0] ,
				ry = original_height / bound[1] ;
			var scaledata = {
					w: scale.w * rx ,
					h: scale.h * ry ,
					x: scale.x * rx ,
					y: scale.y * ry ,
					x2: scale.x2 * rx ,
					y2: scale.y2 * ry ,
					url: url,
					attachType: 2
			}
			var temple = null;
			for( var key in scaledata ){
				temple = scaledata[ key ];
				scaledata[ key ] = isNaN( temple ) ? temple : parseInt( scaledata[ key ] );
			};
			//scale数据格式类似于：{w: 134 ,h: 134 , x: 91 , y: 74 , x2: 225 , y2: 208} w宽度，h高度，x，y左上角坐标，x2，y2右下角坐标
			if( scaledata.w == 0 && scaledata.h == 0 ) {
				// 没有裁剪，直接原图保存
				if( !!jQcrop ) {
					jQcrop.destroy();
					jQcrop = null;
				};
				$previewimg.attr("src", url ).css({
					width: 100,
					height: 100,
					marginLeft: 0,
					marginTop: 0
				});
				BSTYUN.dialog.ok("图片上传成功！");
				return false;
			};
			$.ajax({
				type: 'post',
				url: "/sysAdmin/operate/goodsListAdmin/cutImg",
				data: scaledata ,
				dataType: 'json',
				beforeSend: null,
				complete: null,
				success: function(data){
					var url = data.saveUrl ;
					if( !!jQcrop ) {
						jQcrop.destroy();
						jQcrop = null;
					}
					$show_imgurl.val( url );
					$previewimg.attr("src", url ).css({
						width: 100,
						height: 100,
						marginLeft: 0,
						marginTop: 0
					});
					$cutimg.off().attr("src", url );

					BSTYUN.dialog.ok("图片上传成功！");
				},
				error: function(){
					BSTYUN.dialog.warn("图片上传失败，请检查网络！");
				}
			});
		});
		// 重新初始化裁剪
		function reJcropImg(){
			if( !!jQcrop ) {
				jQcrop.destroy();
				jQcrop = null;
			}
			$cutimg.Jcrop({
				onChange:showPreview,
				onSelect:showPreview // aspectRatio: 1
			},function(){
				jQcrop = this;
			});
			function showPreview(coords){
				if( parseInt(coords.w) > 0 ){
					//计算预览区域图片缩放的比例，通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到
					var rx = panelwidth / coords.w; 
					var ry = panelheight / coords.h;
					//通过比例值控制图片的样式与显示
					$previewimg.css({
						width:Math.round( rx * $cutimg.width() ) + "px",		//预览图片宽度为计算比例值与原图片宽度的乘积
						height:Math.round( ry * $cutimg.height() ) + "px",		//预览图片高度为计算比例值与原图片高度的乘积
						marginLeft:"-" + Math.round( rx * coords.x ) + "px",
						marginTop:"-" + Math.round( ry * coords.y ) + "px"
					});
				};
			};
		};
		// app文件上传
		$device_version.on("change",".file_input",function(){
			var $this = $(this),
				id = $.trim( $this.attr("id") ),
				type = $.trim( $this.attr("data-checktype") ),
				$pretxt = $this.prev(),
				value = $this.val(),
				dirName = $.trim($("#pro_code").val());
			
			if(dirName == '') {
				BSTYUN.dialog.warn("产品编码不能为空，请先填写产品编码！");
			    return false;
			}
			switch ( type ){
				case "android" :
					if( !/.(apk|zip)$/gi.test( value ) ) {
						BSTYUN.dialog.warn("文件类型必须有有效的Android可执行文件！");
					    return false;
					};
					break;
				case "ios" :
					/*if( !/.(deb|ipa|pxl|zip)$/gi.test( value ) ) {
						BSTYUN.dialog.warn("文件类型必须有有效的ios可执行文件！");
					    return false;
					};*/
					if( !/.(ipa|zip)$/gi.test( value ) ) {
						BSTYUN.dialog.warn("文件类型必须有有效的ios可执行文件！");
						return false;
					};
					break;
				case "exe" :
					if( !/.exe$/gi.test( value ) ) {
						BSTYUN.dialog.warn("文件类型必须有有效的windows可执行文件！");
					    return false;
					};
					break;
			};
			BSTYUN.dialog.loading( '文件上传中，请勿刷新页面...' );
			$.ajaxFileUpload({
				url:"/uploadFile/file?objectType=goodsFile&objectName="+dirName,
				secureuri:false,
				fileElementId: id,
				dataType:"json",
				complete: function(){
					BSTYUN.dialog.close();
				},
				success:function(data) {
					if(data.message == "上传文件成功") {
						var path = data.path;
						$pretxt.val( path );
						$pretxt.parent().prev().find(".simple").prop("checked",true);
						// 二维码
						$pretxt.parent().next(".qrcode").show().find(".qrbig").attr("data-qrcodeUrl", data.qrcodeUrl ).attr("src", data.qrcodeSrc );
					}else{
						BSTYUN.dialog.warn(data.message);						
					};
				},
				error:function (data, status, e) {
					BSTYUN.dialog.warn("图片上传失败,请重新选择图片！");
				}
			});
		});
		$device_version.on("mouseenter",".qrsmall",function(){
			var $this = $(this),
				$qrbig = $this.next(),
				url = $.trim( $qrbig.attr("data-qrcodeUrl") ),
				oldrul = $.trim( $qrbig.attr("src") );
			if( oldrul == "/images/admin/kong.gif" ){
				$qrbig.attr("src",url);
			};
			$qrbig.show();
		}).on("mouseleave",".qrsmall",function(){
			var $this = $(this),
				$qrbig = $this.next();
			$qrbig.hide();
		}).on("mouseenter",".qrbig",function(){
			var $this = $(this);
			$this.prev().trigger("mouseenter");
		}).on("mouseleave",".qrbig",function(){
			var $this = $(this);
			$this.prev().trigger("mouseleave");
		});
	},
	submitDownloadFrom: function(){
		var $name = $("#proname"),
		 	$pro_code = $("#pro_code"),
			$img = $("#show_imgurl"),
			$apk = $("#file_android").prev(),
			$apk_qrcode = $apk.parent().next().find(".qrbig"),
			$ios = $("#file_ios").prev(),
			$ios_qrcode = $ios.parent().next().find(".qrbig"),
			$exe = $("#file_pc").prev(),
			$deskurl = $("#desk_url"),
			$slogan = $("#slogan"),
			$decoration = $("#pro_decoration"),
			$pro_adapter = $("#pro_adapter");
		var $device_version = $(".device_version"),
			$checkapk = $device_version.find("input[name=checkapk]"),
			$checkios = $device_version.find("input[name=checkios]"),
			$checkpc = $device_version.find("input[name=checkpc]"),
			$checkdeskurl = $device_version.find("input[name=checkdeskurl]");
		var $operator = $(".operatorbuttons");
		/* 获取数据 */
		function getData(){
			var data = {
					name: $.trim( $name.val() ),
					procode: $.trim( $pro_code.val() ),
					img: $.trim( $img.val() ),
					apk: $.trim( $apk.val() ),
					apkqrcode: $.trim( $apk_qrcode.attr("data-qrcodeUrl") ),
					ios: $.trim( $ios.val() ),
					iosqrcode: $.trim( $ios_qrcode.attr("data-qrcodeUrl") ),
					pcexe: $.trim( $exe.val() ),
					deskurl: $.trim( $deskurl.val() ),
					slogan: $.trim( $slogan.val() ),
					decoration: $.trim( $decoration.val() ),
					adapter: $.trim( $pro_adapter.val() )
				};
			if( !$checkapk.prop("checked") ){ data.apk = ""; data.apkqrcode = ""; };
			if( !$checkios.prop("checked") ){ data.ios = ""; data.iosqrcode = ""; };
			if( !$checkpc.prop("checked") ){ data.pcexe = "";};
			if( !$checkdeskurl.prop("checked") ){ data.deskurl ="" };
			return data;
		};
		/* 校验数据 */
		function checkData( data ){
			if( data.name == "" ){
				BSTYUN.dialog.warn("产品名称不能为空!");
				return false;
			};
			if( data.procode == "" ){
				BSTYUN.dialog.warn("产品编码不能为空!");
				return false;
			};
			if( data.img == "" ){
				BSTYUN.dialog.warn("产品图标不能为空!");
				return false;
			};
			if( !data.apk && !data.ios && !data.pcexe && !data.deskurl ){
				BSTYUN.dialog.warn("请至少上传一个版本!");
				return false;
			};
			if( data.slogan == "" ){
				BSTYUN.dialog.warn("产品口号不能为空!");
				return false;
			};
			if( data.decoration == "" ){
				BSTYUN.dialog.warn("产品描述不能为空!");
				return false;
			};
			if( data.adapter == "" ){
				BSTYUN.dialog.warn("适用场景不能为空!");
				return false;
			};
			return true;
		};
		$operator.on("click",".submit",function(){
			var data = getData();
			if( !checkData( data ) ) return;
			// 判断编辑还是新增
			data["downloadId"] = download_id ? download_id : '';
			
			// ajax提交
			$.ajax({
 				url: '/sysAdmin/operate/downAdmin/saveGoodsDownload',
 				type: 'POST',
 				dataType: 'json',
 				data: data,
 				beforeSend: null,
 				complete: null,
 				success: function(data){
 					if(data.isSuccess){
 						location.href = "/sysAdmin/downAdmin/downManager";
 					};
 				},
 				error: function(error){
 					BSTYUN.dialog.warn("网络异常，请联系管理员");
 				}
 			});
		});
	}
};
$(function(){
	BSTMG.downloadManager.init();
});